from rest_framework_jwt.utils import jwt_payload_handler
import re
from .models import User
from django.contrib.auth.backends import ModelBackend
def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }

def my_jwt_payload_handler(user):
    #获取默认字典
    payload=jwt_payload_handler(user)
    #删除email
    del payload['email']
    #添加mobile属性
    payload['mobile']=user.mobile
    return payload



class MyAuthenticate(ModelBackend):
    #类可以自定义，但是方法名称必须是authenticate(),不能变
    def authenticate(self, request, username=None, password=None, **kwargs):
        #判断是手机号还是用户名
        if re.match(r'^1[3-9]\d{9}$',username):
            #如果是手机号就用手机号查询
            try:
                user = User.objects.get(mobile=username)
            except:
                return None
        else:
            #如果是用户名就用yonghumiing查询
            try:
                user = User.objects.get(username=username)
            except:
                return None
        #判断密码
        if user.check_password(password):
            #密码正确，返回对象
            # request.user = user
            return user
        else:
            #密码错误，返回None
            return None
